package com.arui.yygh.user.api;

import com.alibaba.fastjson.JSONObject;
import com.arui.yygh.common.helper.JwtHelper;
import com.arui.yygh.common.result.Result;
import com.arui.yygh.model.user.UserInfo;
import com.arui.yygh.user.service.UserInfoService;
import com.arui.yygh.user.utils.ConstantWxPropertiesUtil;
import com.arui.yygh.user.utils.HttpClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

//微信操作接口
@Controller
@RequestMapping("/api/ucenter/wx")
public class WeixinApiController {
    @Autowired
    private UserInfoService userInfoService;
    //1.生成微信二维码
    //返回生成二维码需要的参数
    @GetMapping("/getLoginParam")
    @ResponseBody
    public Result genQrConnect(){
        try {
            Map<String,Object> map = new HashMap<>();
            map.put("appId", ConstantWxPropertiesUtil.WX_OPEN_APP_ID);
            map.put("scope","snsapi_login");
            String wxOpenRedirectUrl = ConstantWxPropertiesUtil.WX_OPEN_REDIRECT_URL;
            String encode = URLEncoder.encode(wxOpenRedirectUrl, "utf-8");
            map.put("redirect_uri",encode);
            map.put("state",System.currentTimeMillis()+"");
            return Result.ok(map);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }

    }
    //微信扫码后进行回调的方法
    @GetMapping("callback")
    public  String callBack(String code,String state){
        //第一步 获取临时票据 code
        System.out.println("code:"+code);
        //第二部，拿着code和微信id和密钥，请求固定地址，得到两个值
        //使用code和appid以及appscrect换取access_token
        StringBuffer baseAccessTokenUrl = new StringBuffer()
                .append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");
        // %s 占位符
        String accessTokenUrl = String.format(baseAccessTokenUrl.toString(),
                ConstantWxPropertiesUtil.WX_OPEN_APP_ID,
                ConstantWxPropertiesUtil.WX_OPEN_APP_SECRET,
                code);
        //使用httpclient去请求这个地址
        try {
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
            System.out.println(accessTokenInfo);
            //从返回的字符串获取两个值 open Id 和 access_token
            JSONObject jsonObject = JSONObject.parseObject(accessTokenInfo);
            String access_token = jsonObject.getString("access_token");
            String openid = jsonObject.getString("openid");
            //判断数据库中是否有扫码人的信息
            //根据openId判断
            UserInfo userInfo = userInfoService.selectWxInfoOpenId(openid);
            if (userInfo==null){
                //拿着openId 和 access_token请求微信地址，得到扫描人信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(baseUserInfoUrl, access_token, openid);
                String resultInfo = HttpClientUtils.get(userInfoUrl);
                System.out.println(resultInfo);
                JSONObject resultInfojsonObject = JSONObject.parseObject(resultInfo);
                //解析用户信息
                //用户信息
                String nickname = resultInfojsonObject.getString("nickname");
                //用户头像
                String headimgurl = resultInfojsonObject.getString("headimgurl");

                //扫码人的信息添加到数据库

                userInfo = new UserInfo();
                userInfo.setNickName(nickname);
                userInfo.setOpenid(openid);
                userInfo.setStatus(1);

                userInfoService.save(userInfo);
            }



            //返回name和token字符串
            Map<String,String> map = new HashMap<>();
            String name = userInfo.getName();
            if(StringUtils.isEmpty(name)) {
                name = userInfo.getNickName();
            }
            if(StringUtils.isEmpty(name)) {
                name = userInfo.getPhone();
            }
            map.put("name", name);
            //判断UserInfo是否有手机号,如果手机号为空，返回openId
            //如果手机号不为空，返回openId值是空字符串
            //前端判断，如果openId不为空，绑定手机号，如果Id为空，不需要绑定手机号
            if(StringUtils.isEmpty(userInfo.getPhone())) {
                map.put("openid", userInfo.getOpenid());
            } else {
                map.put("openid", "");
            }
            String token = JwtHelper.createToken(userInfo.getId(), name);
            map.put("token", token);
            System.out.println(map.get("openid"));
            return "redirect:" + ConstantWxPropertiesUtil.YYGH_BASE_URL + "/weixin/callback?token="+map.get("token")+"&openid="+map.get("openid")+"&name="+URLEncoder.encode((String)map.get("name"),"utf-8");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }


    }

    //2.得到扫码人的信息
}
